/*global tinymce:true */
tinymce.PluginManager.add('emrDesign', function (editor) {
	var enabled = {}, visualBlocksMenuItem;

	function toggleActiveState(name) {
		return function () {
			var self = this;
			self.active(enabled[name]);
			editor.on(name, function () {
				self.active(editor.dom.hasClass(editor.getBody(), 'mce-' + name));
			});
		};
	}

	function addMenuItem(text, name) {

		editor.addCommand('mce' + name, function () {
			var dom = editor.dom;

			// Toggle on/off visual blocks while computing previews
			editor.on("PreviewFormats AfterPreviewFormats", function (e) {
				if (enabled[name]) {
					dom.toggleClass(editor.getBody(), 'mce-' + name, e.type == "afterpreviewformats");
				}
			});

			dom.toggleClass(editor.getBody(), 'mce-' + name);
			editor[name] = enabled[name] = editor.dom.hasClass(editor.getBody(), 'mce-' + name);

			if (visualBlocksMenuItem) {
				visualBlocksMenuItem.active(dom.hasClass(editor.getBody(), 'mce-' + name));
			}
			editor.fire(name);
		});

		editor.addMenuItem(name, {
			text: text,
			cmd: 'mce' + name,
			onPostRender: toggleActiveState(name),
			selectable: true,
			context: 'emr',
			prependToContext: true
		});
	}


	addMenuItem("页脚", "pagefooter");
	addMenuItem("页眉", "pageheader");

	editor.on('init', function () {
		if (editor.settings.pageheader) {
			editor.execCommand('mcepageheader', false, null, {skip_focus: true});
		}

		if (editor.settings.pagefooter) {
			editor.execCommand('mcepagefooter', false, null, {skip_focus: true});
		}
	});
});
